<?php
/**
 * CreateUser:zlh
 * CreateTime:2022/1/15
 * Remark:该类为员工相关操作控制器
 */
namespace App\Http\Controllers\Staff;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\StaffConsts\StaffConsts;
use App\Func\EncryptionFunc;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Http\Controllers\Controller;
use App\Http\Requests\ListBasicRequest;
use App\Http\Requests\Staff\AddStaffPost;
use App\Http\Requests\Staff\AuthorizeStaffGet;
use App\Http\Requests\Staff\AuthorizeStaffPost;
use App\Http\Requests\Staff\EditCurrentStaffPwd;
use App\Http\Requests\Staff\ListStaffGet;
use App\Models\Company\CompanyModel;
use App\Models\Department\DepartmentModel;
use App\Models\Log\DingTalkBindLog;
use App\Models\Position\PositionModel;
use App\Models\Staff\StaffDepartmentModel;
use App\Models\Staff\StaffModel;
use App\Service\Staff\StaffDepartmentService;
use App\Service\Staff\StaffService;
use App\Tools\DingTalk\DingTalkDeptUserFacade;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Mockery\Exception;

class StaffController extends Controller
{
    private StaffService $_staffService;
    private StaffDepartmentService $_staffDepartmentService;

    public function __construct()
    {
        $this->middleware([
            'staffLeg'
        ]);
        $this->_staffService = new StaffService();
        $this->_staffDepartmentService = new StaffDepartmentService();
    }

    public function editCurrentStaffPwd(EditCurrentStaffPwd $editCurrentStaffPwd){
        $staffData = $editCurrentStaffPwd->all();
        $staffId = TokenFuc::getCurrentStaffInfo()['staff_id'];
        $this->_staffService->editStaffPwd($staffId,$staffData);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '修改密码成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    public function addStaff(AddStaffPost $request): \Illuminate\Http\JsonResponse
    {
        $this->_staffService->addStaffService($request->all());
        return ResponseFunc::returnJson(
            'ok',
            null,
            '新建用户成功',
            ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
        );
    }

    /**
     * 获取用户详情
     * @param int $staffId
     */
    public function getStaffDetail(int $staffId): \Illuminate\Http\JsonResponse
    {
        return ResponseFunc::returnJson(
            'ok',
            $this->_staffService->getStaffDetail($staffId),
            "获取详情成功",
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 获取用户列表
     * @param ListStaffGet $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStaffList(ListStaffGet $request): \Illuminate\Http\JsonResponse
    {
        $pFilters = $request->get('filters');
        $pageSize = $request->get('page_size');
        $filters = $pFilters ? json_decode($pFilters,true) : [];
        $currentInfo = TokenFuc::getCurrentStaffInfo();
        return ResponseFunc::returnJson(
            'ok',
            $this->_staffService->getStaffList($currentInfo['company_id'],$filters,$pageSize),
            '获取用户列表成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * @param int $staffId
     * @return \Illuminate\Http\JsonResponse
     */
    public function editStaffBasic(int $staffId): \Illuminate\Http\JsonResponse
    {
        $staffData = request()->all();
        $this->_staffService->editStaffBasic($staffId,$staffData);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '编辑用户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }


    public function editCurrentStaffBasic(){
        $staffData = request()->all();
        $staffId = TokenFuc::getCurrentStaffInfo()['staff_id'];
        $this->_staffService->editCurrentStaffBasic($staffId,$staffData);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '编辑用户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }


    /**
     * 新增部门职位
     * @param int $staffId
     * @return \Illuminate\Http\JsonResponse
     */
    public function addStaffDepartment(int $staffId): \Illuminate\Http\JsonResponse
    {
        $staffDepartmentData = request()->all();
        $staffDepartmentData['departments']['staff_id'] = $staffId;
        $staffDepartmentId = $this->_staffDepartmentService->addStaffDepartment($staffDepartmentData['departments']);
        return ResponseFunc::returnJson(
            'ok',
            $staffDepartmentId,
            '新增部门职位成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }


    /**
     * 删除部门职位
     * @param int $staffId
     * @param int $staffDepartmentId
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteStaffDepartment(int $staffId,int $staffDepartmentId): \Illuminate\Http\JsonResponse
    {
        $staffDepartmentData['staffId'] = $staffId;
        $staffDepartmentData['staffDepartmentId'] = $staffDepartmentId;
        $this->_staffDepartmentService->deleteStaffDepartment($staffDepartmentData);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '删除用户职位成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }


    /**
     * 修改员工部门职位
     * @param int $staffId
     * @param int $staffDepartmentId
     * @return \Illuminate\Http\JsonResponse
     */
    public function editStaffDepartment(int $staffId,int $staffDepartmentId): \Illuminate\Http\JsonResponse
    {
        $staffDepartmentData = request()->all();
        $staffDepartmentData['staffId'] = $staffId;
        $staffDepartmentData['staffDepartmentId'] = $staffDepartmentId;
        $this->_staffDepartmentService->editStaffDepartment($staffDepartmentData);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '编辑用户职位成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 删除用户
     * @param int $staffId
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteStaff(int $staffId): \Illuminate\Http\JsonResponse
    {
        $this->_staffService->deleteStaff($staffId);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '删除用户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 启用用户
     * @param int $startStaffId
     */
    public function startStaff(int $startStaffId): \Illuminate\Http\JsonResponse
    {
        $startStaffData['staffId'] = $startStaffId;
        $this->_staffService->startStaff($startStaffData);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '启用用户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 停用用户
     * @param int $stopStaffId
     */
    public function stopStaff(int $stopStaffId): \Illuminate\Http\JsonResponse
    {
        $this->_staffService->stopStaff($stopStaffId);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '停用用户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 批量删除用户
     * @return \Illuminate\Http\JsonResponse
     */
    public function bulkDeleteStaff(): \Illuminate\Http\JsonResponse
    {
        $staffIds = \request()->post('staff_ids');
        $this->_staffService->bulkDeleteStaff($staffIds);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '批量删除用户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    public function getMediatorList(ListBasicRequest $request){
        try {
            $pFilters = $request->get('filters');
            $pageSize = $request->get('page_size');
            $filters = $pFilters ? json_decode($pFilters,true) : [];
            $data = $this->_staffService->getMediatorList($filters,$pageSize);
            return ResponseFunc::returnJson(
                'ok',
                $data,
                '获取调解员列表成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            dd($exception);
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取调解员列表失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 获取当前登录用户
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCurrentStaff(): \Illuminate\Http\JsonResponse
    {
        // 获取当前用户 Ids
        $staffInfo = TokenFuc::getCurrentStaffInfo();
        // 获取当前登录的公司部门等信息

        $departmentStaffModel = new StaffDepartmentModel();
        $positionInfo = $departmentStaffModel
            ->select(['position_id'])
            ->where('department_id',$staffInfo['department_id'])
            ->where('staff_id',$staffInfo['staff_id'])
            ->first();
        $staffInfo['position_id'] = $positionInfo['position_id'] ?? "-";


        return ResponseFunc::returnJson(
            'ok',
            $this->_staffService->getCurrentStaffByCurrentInfo($staffInfo),
            '获取当前登录用户',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    public function AuthorizeDetail(AuthorizeStaffGet $request): \Illuminate\Http\JsonResponse
    {
        // 如果不是管理员禁用授权接口
        $staffInfo = TokenFuc::getCurrentStaffInfo();
//        if($staffInfo['staff_type']!= StaffConsts::ADMIN_STAFF_TYPE){
//            return ResponseFunc::returnJson(
//                'error',
//                null,
//                '缺少权限',
//                ResponseStatusConsts: :UNAUTHORIZED_401_RESPONSE_STATUS
//            );
//        }
        return ResponseFunc::returnJson(
            'ok',
            $this->_staffService->AuthorizeDetail($request->all()),
            '授权用户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 用户授权
     */
    public function AuthorizeStaff(AuthorizeStaffPost $request): \Illuminate\Http\JsonResponse
    {
        // 如果不是管理员禁用授权接口
        $staffInfo = TokenFuc::getCurrentStaffInfo();
        if($staffInfo['staff_type']!= StaffConsts::ADMIN_STAFF_TYPE){
            return ResponseFunc::returnJson(
                'error',
                null,
                '缺少权限',
                ResponseStatusConsts::UNAUTHORIZED_401_RESPONSE_STATUS
            );
        }
        $this->_staffService->AuthorizeStaff($request->all());
        return ResponseFunc::returnJson(
            'ok',
            null,
            '授权用户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    public function snsGetDingTalkUserId(){
//        $unionId = DingTalkDeptUserFacade::getDingTalkScanOrCodes($code);
//        $dingTalkId = DingTalkDeptUserFacade::getDingTalkUserIdByUnionId($unionId);
    }

    /**
     * 钉钉绑定用户
     */
    public function bindDingTalk($tokenV2){
        $data = request()->all();
        $code = $data['code'] ?? "";
        $staffToken = $data['p'] ?? "";
        $ivT = $data['t'] ?? "";
        $errMsg = '登录成功';
        // url 参数定义
        $auto = "true";
        $ok = "true";
        $t = "";
        $rid = "";
        // 获取钉钉用户ID
        try {
            DB::beginTransaction();
            $unionId = DingTalkDeptUserFacade::getDingTalkScanOrCodes($code);
            $dingTalkUserId = DingTalkDeptUserFacade::getDingTalkUserIdByUnionId($unionId);
            // 获取当前登录用户信息
            $iv = EncryptionFunc::getOpensslIv(1,$ivT);
            $urlIv = EncryptionFunc::getOpensslIv(2,$ivT);
            $decryBindStr =  EncryptionFunc::decryptOpenssl($staffToken,$iv);
            $decryBindArr = json_decode($decryBindStr,true);
            $decryBindUrl = EncryptionFunc::decryptOpenssl($data['u'],$urlIv);
            $userId = Redis::get($decryBindArr['token']) ?? 0;
            # by breezeer @2022.08.09 => 单点登录
            #

            app()->gcProviderVerifyUserVisitPermission->setUserVisitPermission($userId,$tokenV2);
            $t = $decryBindArr['token'];
            $rid = $decryBindArr['rid'];
            // 查看当前登录用户的公司
            $company_id =  $this->_staffService->getStaffDetailCustom($userId,['company_id'])['company_id'] ?? 0;
            if(!$company_id){
                $auto = 'false';
                $ok = 'false';
                $errMsg = '登录信息错误公司不存在';
                $returnUrl = $decryBindUrl."?auto=$auto&ok=$ok&msg=$errMsg&t=$t&rid=$rid";
                header("Location: $returnUrl");
                die();
            }
            // 查看当前钉钉账号是否已经绑定过了
            $isExists = $this->_staffService->getDingTalkIdIsCompanyBind($dingTalkUserId,$company_id);
            if($isExists){
                $auto = 'false';
                $ok = 'false';
                $errMsg = '当前钉钉已经被绑定过';
                $returnUrl = $decryBindUrl."?auto=$auto&ok=$ok&msg=$errMsg&t=$t&rid=$rid";
                header("Location: $returnUrl");
                die();
            }
            // 绑定用户钉钉修改用户状态
            $this->_staffService->bindDingTalk($dingTalkUserId,$unionId,$userId);
            DB::commit();
        }catch (Exception $exception){
            $errMsg = $exception->getMessage();
            DB::rollBack();
        }
        // 保存日志
        $log = new DingTalkBindLog();
        $log->setAttribute('ding_talk_user_id', $dingTalkUserId);
        $log->setAttribute('ding_talk_unionid', $unionId);
        $log->setAttribute('error_msg', $errMsg);
        $log->setAttribute('created_at', time());
        $log->setAttribute('staff_id', $userId);
        $log->save();
        $returnUrl = $decryBindUrl."?auto=$auto&ok=$ok&msg=$errMsg&t=$t&rid=$rid&v2=$tokenV2";
        header("Location: $returnUrl");
        die();
    }


}
